package com.enba.boot.mq.sender.activemq.config;

import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;

@ConditionalOnClass(JmsMessagingTemplate.class)
public class ActiveMQConfig {

  public static final String CLUSTE_FACTORY_BEAN_NAME = "clusterListenerContainerFactory";
  public static final String BROADCAST_FACTORY_BEAN_NAME = "broadcastListenerContainerFactory";

  public static final String CLUSTER_TEMPLATE_BEAN_NAME = "clusterJmsTemplate";
  public static final String BROADCAST_TEMPLATE_BEAN_NAME = "broadcastJmsTemplate";

  // 集群消费连接工厂配置

  @Bean(CLUSTE_FACTORY_BEAN_NAME)
  public DefaultJmsListenerContainerFactory clusterJmsListenerContainerFactory(
      DefaultJmsListenerContainerFactoryConfigurer configurer,
      ConnectionFactory connectionFactory) {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
    configurer.configure(factory, connectionFactory);
    factory.setPubSubDomain(false);
    return factory;
  }

  @Bean(CLUSTER_TEMPLATE_BEAN_NAME)
  public JmsMessagingTemplate clusterJmsTemplate(ConnectionFactory connectionFactory) {
    // 创建 JmsTemplate 对象
    JmsTemplate template = new JmsTemplate(connectionFactory);
    template.setPubSubDomain(false);
    template.setDeliveryMode(DeliveryMode.PERSISTENT);
    // 创建 JmsMessageTemplate
    return new JmsMessagingTemplate(template);
  }

  // 广播消费连接工厂配置

  @Bean(BROADCAST_FACTORY_BEAN_NAME)
  public DefaultJmsListenerContainerFactory broadcastJmsListenerContainerFactory(
      DefaultJmsListenerContainerFactoryConfigurer configurer,
      ConnectionFactory connectionFactory) {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
    configurer.configure(factory, connectionFactory);
    factory.setPubSubDomain(true);
    return factory;
  }

  @Bean(BROADCAST_TEMPLATE_BEAN_NAME)
  public JmsMessagingTemplate broadcastJmsTemplate(ConnectionFactory connectionFactory) {
    JmsTemplate template = new JmsTemplate(connectionFactory);
    template.setPubSubDomain(true);
    template.setDeliveryMode(DeliveryMode.PERSISTENT);
    return new JmsMessagingTemplate(template);
  }
}
